from pymysql import connect
from utils.log import logger_sql
import threading


class Py_Mysql():
    def Start(self):
        # 连接数据
        self.conn = connect(host='localhost', user='root',
                            password='soloman', database='movie_collect', port=3306)
        # 创建一个cursor对象
        self.cursor = self.conn.cursor()

    # 创建表
    def Create(self, sql, table):
        self.Start()
        try:
            self.cursor.execute(sql)
            logger_sql.info(f'{table}表创建完成')
        except Exception as e:
            if '1050' not in str(e):
                logger_sql.info(e)
        self.Close()

    # 数据插入(单条)
    def Insert_OneData(self, sql):
        self.Start()
        try:
            self.cursor.execute(sql)
            self.conn.commit()
        except Exception as e:
            logger_sql.error(e)
            self.conn.rollback()
        self.Close()

    # 数据插入(批量)
    def Insert_Data(self, sql, data):
        self.Start()
        try:
            self.cursor.executemany(sql, data)
            self.conn.commit()
        except Exception as e:
            logger_sql.error(e)
            self.conn.rollback()
        self.Close()

    # 数据查询
    def Select_All(self, sql):
        self.Start()
        try:
            self.cursor.execute(sql)
            data = self.cursor.fetchall()
            self.conn.commit()
            return data
        except Exception as e:
            logger_sql.error(e)
        self.Close()

    # 更改数据
    def Update(self, sql):
        self.Start()
        try:
            self.cursor.execute(sql)
            self.conn.commit()
        except Exception as e:
            logger_sql.error(e)
        self.Close()

    # 删除数据
    def Delete(self, sql):
        self.Start()
        try:
            self.cursor.execute(sql)
            self.conn.commit()
        except Exception as e:
            logger_sql.error(e)
            self.conn.rollback()
        self.Close()

    def Close(self):
        # 断开连接
        self.cursor.close()
        self.conn.close()
